﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LogManager.Windows
{
    public class WindowsEventQueryBuilder
    {
        private string _query = "*";
        
        public string CreateQuery()
        {
            return _query;
        }

        public WindowsEventQueryBuilder Where(string condition)
        {
            _query = string.Format(_query == "*" ? "{0}[System[{1}]]" : "{0} and {1}", _query, condition);
            return this;
        }

        public static string UserCondition(string userId)
        {
            return string.Format("Security[@UserID='{0}']", userId);
        }

        public static string TimeRangeCondition(DateTime start,DateTime end)
        {
            return string.Format("TimeCreated[@SystemTime>='{0}' and @SystemTime<='{1}']", FormatQueryDate(start), FormatQueryDate(end));
        }

        public static string EventTypeCondition(string eventType)
        {
            return string.Format("(EventID={0})", eventType);
        }

        /// <summary>
        /// Creates a condition for a timedifference
        /// </summary>
        /// <param name="ms">Miliseconds</param>
        /// <returns></returns>
        public static string TimeDiffCondition(int ms)
        {
            return string.Format("TimeCreated[timediff(@SystemTime) <= {0}]", ms);
        }

        public static string LevelCondition(byte level)
        {
            return string.Format("(Level={0})", level);
        }

        /// <summary>
        /// Formats a date so that it fits for a event log query
        /// </summary>
        /// <param name="date">The date to format</param>
        /// <returns>Date formatted as string</returns>
        private static string FormatQueryDate(DateTime date)
        {
            return date.ToString("yyyy-MM-ddThh:mm:00.999Z");
        }
    }
}
